import router from './router'
import axios from 'axios'
import store from './vuex'

const baseUrl = process.env.NODE_ENV === 'development' ? 'https://192.168.0.181:8101/login?returnURL=':'http://68.202.4.5:8101/login?returnURL=';
const url = process.env.NODE_ENV === 'development' ? 'https://www.easy-mock.com/mock/5b742307ee973f101f9e9775/datashow/platform/common/validToken':'/xz/loginToken';

router.beforeEach((to, from, next) => {
  let token = getUrlParam('token');

  if(token == null || token == ''){
    token = getCookie('token');
  }

  if(!token){
    window.location.href = baseUrl + window.location.href.replace(window.location.search,'');
  }else{
    axios.get(url+"?token="+token).then(function(res){
      // 判断token是否有效
      if(res.data){
        document.cookie = 'token='+ token;
        store.commit('SET_TOKEN',token);
      }else{
        window.location.href = baseUrl + window.location.href.replace(window.location.search,'');
      }
      // 判断当前是否是登录页面
      if (to.path === '/login') {
        next({ path: '/' });
      } else {
        next()
      }
    }).catch(function(res){
      window.location.href = baseUrl + window.location.href.replace(window.location.search,'');
    })
  }

  // if(token == null||token == ''){
  //   // 判断是否有token
  //   if (getCookie('token')) { 
  //     if (to.path === '/login') {
  //       next({ path: '/' });
  //     } else {
  //       next()
  //     }
  //   } else {
  //     window.location.href = baseUrl + window.location.href;
  //   }
  // }else{
  //   axios.get(url+"?token="+token).then(function(res){
  //     // 判断token是否有效
  //     if(res.data){
  //       document.cookie = 'token='+ token;
  //       store.commit('SET_TOKEN',token);
  //     }else{
  //       window.location.href = baseUrl + window.location.href.replace(window.location.search,'');
  //     }
  //     // 判断当前是否是登录页面
  //     if (to.path === '/login') {
  //       next({ path: '/' });
  //     } else {
  //       next()
  //     }
  //   }).catch(function(res){
  //     window.location.href = baseUrl + window.location.href.replace(window.location.search,'');
  //   })
  // }
});


function getCookie(name) {
  let arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
  if(arr=document.cookie.match(reg))
    return unescape(arr[2]);
  else
    return null;
};
// 获取url参数方法
function getUrlParam(name) { 
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
  var r = window.location.search.substr(1).match(reg); 
  if (r != null) return unescape(r[2]); return null; 
} 